package com.andy.blog.admin.service.impl;

import com.andy.blog.admin.dto.CategoryDTO;
import com.andy.blog.admin.service.CategoryBusService;
import com.andy.blog.common.enums.DeleteTypeEnum;
import com.andy.blog.common.page.PageUtilsDTO;
import com.andy.blog.common.utils.TransformUtils;
import com.andy.blog.dal.domain.CategoryDO;
import com.andy.blog.dal.service.ArticleDalService;
import com.andy.blog.dal.service.CategoryDalService;
import com.andy.blog.dal.vo.ArticleVO;
import com.andy.blog.dal.vo.CategoryVO;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created by andy on 2023/6/21 12:44
 */
@Service
public class CategoryBusServiceImpl implements CategoryBusService {

    @Resource
    private CategoryDalService categoryDalService;

    @Resource
    private ArticleDalService articleDalService;


    @Override
    public PageUtilsDTO<CategoryDTO> selectListByPage(CategoryVO categoryVO) {
        IPage<CategoryDO> categoryDOIPage = categoryDalService.selectListByPage(categoryVO);
        List<CategoryDTO> list = TransformUtils.transformList(categoryDOIPage.getRecords(), CategoryDTO.class);
        return PageUtilsDTO.build(categoryDOIPage.getTotal(), list);
    }

    @Override
    public void addCategory(CategoryVO categoryVO) {
        categoryDalService.addCategory(categoryVO);
    }

    @Override
    public CategoryDTO selectCategoryById(Long id) {
        CategoryDO categoryDO = categoryDalService.getById(id);
        return TransformUtils.transform(categoryDO, CategoryDTO.class);
    }

    @Override
    public void updateCategory(CategoryVO categoryVO) {
        categoryDalService.updateById(categoryVO);
    }

    @Override
    public List<CategoryDTO> selectList(CategoryVO categoryVO) {
        List<CategoryDO> dataList = categoryDalService.selectList(categoryVO);
        return TransformUtils.transformList(dataList, CategoryDTO.class);
    }

    @Override
    public List<CategoryDTO> listCategoryVO() {
        List<CategoryDO> categoryDOS = categoryDalService.selectList(CategoryVO.builder().build());

        List<CategoryDTO> categoryDTOS = TransformUtils.transformList(categoryDOS, CategoryDTO.class);
        for (CategoryDTO categoryDTO : categoryDTOS) {
            Long articleCount = articleDalService.selectArticleCount(ArticleVO.builder()
                    .categoryId(categoryDTO.getId())
                    .isDeleted(DeleteTypeEnum.DELETE_N.getCode())
                    .build());
            categoryDTO.setArticleCount(articleCount);
        }

        return categoryDTOS;
    }
}
